import { getUser, getSidebarMenus } from '@/api/userinfo'
import router, { resetRouter } from '@/router'
const state = {
  user: {},
  menus: [],
  roles: [],
  name: '',
  avatar: '',
  introduction: '',
  token: ''
}

const mutations = {
  SET_USER: (state, user) => {
    state.user = user
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  getUser({ dispatch, commit, state }) {
    return new Promise((resolve, reject) => {
      getUser().then(res => {
        console.log(res, 'res')
        commit('SET_USER', res.data)
        commit('SET_ROLES', res.data.roles)
        getSidebarMenus().then((menus) => {
          dispatch('permission/generateMainRoutes', menus, { root: true }).then((routes) => {
            router.addRoutes(routes)
          })
        })
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getSidebarMenus({ commit, state }) {
    return new Promise((resolve, reject) => {
      getSidebarMenus().then(menus => {
        if (!menus || !menus.length) {
          reject('no menus.')
        }
        commit('SET_MENUS', menus)
        resolve(menus)
      }).catch(error => {
        reject(error)
      })
    })
  },
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const { roles } = await dispatch('getUser')
      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },
  removeUserinfo({ commit }) {
    commit('SET_USER', {})
    commit('SET_MENUS', [])
    commit('SET_ROLES', [])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
